package com.hnust.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.RenderedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.List;

import javax.imageio.ImageIO;

import com.hnust.config.YamlReader;
import com.spire.doc.Document;
import com.spire.doc.documents.DocumentObjectType;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;
import com.spire.doc.interfaces.ICompositeObject;
import com.spire.doc.interfaces.IDocumentObject;
import net.coobird.thumbnailator.ThumbnailParameter;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.util.ThumbnailatorUtils;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.stereotype.Component;

@Component
public class PictureIO {

	public static void doPic(Document document) throws IOException, MyException {
		//创建Queue对象 (队列)
		Queue nodes = new LinkedList();
		nodes.add(document);
		//创建List对象（Map类型对象，以String类型为键，以Object类型为值的键值对）
		List images = new ArrayList();
		List<String> imagesNames = new ArrayList<>();
		List<Float> widthList = new ArrayList();
		List<Float> hightList = new ArrayList();
		int ai = 1;
		int con = 0;
		int param_num = 0;
		File picdir = new File(System.getProperty("user.dir") + "/assets/pictures");
		//System.getProperty("user.dir"):默认定位到的当前用户目录("user.dir")（即工程根目录）
		//picdir = A:\idea\github\tes-teacher-endback-new\assets\pictures
		if (!picdir.exists()) {
			picdir.mkdir();
		}

		while (nodes.size() > 0) {
			ICompositeObject node = (ICompositeObject) nodes.poll();
			if (param_num == 0 && ai++ == 3) {
				param_num = 1;
			}

			int exist = 0;

			for (int i = 0; i < node.getChildObjects().getCount(); i++) {
				IDocumentObject child = node.getChildObjects().get(i);
				if (param_num != 0) {
					exist = 1;
				}
				if (child instanceof ICompositeObject) {
					nodes.add((ICompositeObject) child);
					//获取 图片并添加到list
					if (child.getDocumentObjectType() == DocumentObjectType.Picture) {
						DocPicture picture = (DocPicture) child;
						float w = picture.getWidth();
						float h = picture.getHeight();
						picture.setWidth(w);
						picture.setHeight(h);
						widthList.add(w);
						hightList.add(h);

						images.add(picture.getImage());
						//获取图片名称
						String name = IDUtil.getPrimaryKey();
//						TextRange text = (TextRange) node.getChildObjects().get(i);
						TextRange text = new TextRange(document);
						//String picPath = "http://" + YamlReader.instance.getValueByKey("pic.url") + ":" + YamlReader.instance.getValueByKey("pic.port") + "/pic/";
						String picPath = "http://"+ YamlReader.instance.getValueByKey("pic.url")+"/";
						imagesNames.add(name);


						//将图片保存为PNG格式
						for (int j = 0; j < images.size(); j++) {
							//设置图片宽高
							int width = Integer.parseInt(String.valueOf((int)Math.ceil(widthList.get(j))));
							int height = Integer.parseInt(String.valueOf((int)Math.ceil(hightList.get(j))));
							/** 压缩之后临时存放位置 */
							String picFile = picdir +"/"+ imagesNames.get(j)+".png";
							//picFile = A:\idea\github\tes-teacher-endback-new\assets\pictures\图片名.png
//			ImageIO.write(tag, "png", new File(picFile));

							//使用框架生成图片
							Thumbnails.of((BufferedImage) images.get(j))
									.size((int)(width*1.5), (int)(height*1.5))
									.toFile(new File(picFile));
						}

						//fastdfs图片上传路径
						String picurl =picdir+"/"+name+".png";

						// 加载fastDFS客户端的配置 文件
						ClientGlobal.initByProperties("config/fastdfs-client.properties");
						//创建tracker的客户端
						TrackerClient tracker = new TrackerClient();
						TrackerServer trackerServer = tracker.getConnection();
						StorageServer storageServer = null;
						//定义storage的客户端
						StorageClient1 client = new StorageClient1(trackerServer, storageServer);
						//文件元信息
						NameValuePair[] metaList = new NameValuePair[1];
						metaList[0] = new NameValuePair("fileName", "1.png");
						//获取文件后缀名
						//String file_ext_name = upImageName.substring(upImageName.lastIndexOf('.')+1);
						//执行上传
						String fileId = client.upload_file1(picurl, ".png", metaList);
						//imageName=fileId;
						System.out.println(fileId);
						System.out.println("upload success. file id is: "+"http://123.57.242.140/" + fileId);
						//关闭trackerServer的连接
						trackerServer.close();

						text.setText(("<img style=\"width: "+(String.format("%.2f",picture.getWidth()*1.5))+"px;height: "+(String.format("%.2f",picture.getHeight()*1.5))+"px;\" src=\"" + picPath + fileId+"\"/>").replace(" ","&778604985"));
//						document.replace(text.getText(), "<img src=\"" + picPath + name+".png\"/>" + text.getText(), true, false);
						node.getChildObjects().insert(i, text);
						node.getChildObjects().remove(child);
					}
				}
			}
		}


	}
}
